package com.lucifer.treasure.enchant.effect;

import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.fabricmc.fabric.api.entity.event.v1.ServerLivingEntityEvents;
import net.minecraft.enchantment.EnchantmentEffectContext;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.enchantment.EnchantmentLevelBasedValue;
import net.minecraft.enchantment.effect.EnchantmentEntityEffect;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.item.ItemStack;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.registry.entry.RegistryEntry;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.math.Vec3d;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public record GloomCurseEnchantmentEffect(EnchantmentLevelBasedValue curse) implements EnchantmentEntityEffect {
    public static final MapCodec<GloomCurseEnchantmentEffect> CODEC = RecordCodecBuilder.mapCodec(instance ->
            instance.group(
                    EnchantmentLevelBasedValue.CODEC.fieldOf("curse").forGetter(GloomCurseEnchantmentEffect::curse)
            ).apply(instance, GloomCurseEnchantmentEffect::new)
    );

    // 配置常量
    private static final double BASE_ACTIVATION_CHANCE = 0.15; // 15%基础激活概率
    private static final double BASE_APPLY_CHANCE = 0.4; // 40%应用效果概率
    private static final int MIN_EFFECTS = 1; // 最少1个效果
    private static final int MAX_EFFECTS = 2; // 最多2个效果
    private static final int EFFECT_DURATION = 120; // 6秒持续时间

    public static void initialize() {
        // 监听实体受伤事件 - 但这次是攻击者触发
        ServerLivingEntityEvents.AFTER_DAMAGE.register((victim, source, baseDamage, actualDamage, blocked) -> {
            handleGloomCurse(victim, source);
        });
    }

    /**
     * 处理阴暗诅咒逻辑 - 攻击时对被攻击者施加负面效果
     */
    private static void handleGloomCurse(LivingEntity victim, DamageSource source) {
        if (victim.getWorld().isClient()) {
            return; // 只在服务器端处理
        }

        // 检查攻击者
        Entity attacker = source.getAttacker();
        if (!(attacker instanceof LivingEntity livingAttacker)) {
            return;
        }

        // 检查攻击者是否有GloomCurse附魔（检查所有盔甲部件）
        boolean hasGloomCurse = false;
        int maxLevel = 0;

        // 检查所有盔甲部件，但不叠加概率，只取最高等级
        for (EquipmentSlot slot : new EquipmentSlot[]{EquipmentSlot.HEAD, EquipmentSlot.CHEST, EquipmentSlot.LEGS, EquipmentSlot.FEET}) {
            int level = getGloomCurseLevel(livingAttacker, slot);
            if (level > 0) {
                hasGloomCurse = true;
                maxLevel = Math.max(maxLevel, level);
            }
        }

        if (!hasGloomCurse) {
            return; // 攻击者没有GloomCurse附魔
        }

        // 计算激活概率（等级越高概率越大，但多件装备不叠加）
        double activationChance = BASE_ACTIVATION_CHANCE + (maxLevel - 1) * 0.05; // 每级增加5%

        if (livingAttacker.getWorld().getRandom().nextDouble() < activationChance) {
            applyGloomCurse(livingAttacker, victim, maxLevel);
        }
    }

    /**
     * 应用阴暗诅咒效果 - 对被攻击者施加负面效果
     */
    private static void applyGloomCurse(LivingEntity attacker, LivingEntity victim, int level) {
        List<RegistryEntry<StatusEffect>> negativeEffects = getNegativeEffects();
        Collections.shuffle(negativeEffects);

        int appliedEffects = 0;
        int maxEffectsForLevel = Math.min(MIN_EFFECTS + (level - 1), MAX_EFFECTS);

        for (RegistryEntry<StatusEffect> effect : negativeEffects) {
            if (effect == null) {
                continue;
            }

            // 检查是否应该应用这个效果
            if (appliedEffects < MIN_EFFECTS ||
                    victim.getWorld().getRandom().nextDouble() < BASE_APPLY_CHANCE) {

                // 效果强度和持续时间根据等级调整
                int amplifier = Math.max(0, level - 1); // 1级=0强度，2级=1强度，3级=2强度
                int duration = EFFECT_DURATION + (level - 1) * 20; // 每级增加1秒

                StatusEffectInstance effectInstance = new StatusEffectInstance(
                        effect, duration, amplifier, false, true, true);
                victim.addStatusEffect(effectInstance);

                appliedEffects++;
                if (appliedEffects >= maxEffectsForLevel) {
                    break;
                }
            }
        }

        // 播放诅咒音效（在被攻击者位置）
        victim.getWorld().playSound(null, victim.getX(), victim.getY(), victim.getZ(),
                SoundEvents.ENTITY_WITCH_HURT, SoundCategory.HOSTILE,
                0.6f, 0.8f + victim.getWorld().getRandom().nextFloat() * 0.4f);

        // 生成诅咒粒子效果
        if (victim.getWorld() instanceof ServerWorld serverWorld) {
            // 在被攻击者周围生成黑色烟雾粒子
            serverWorld.spawnParticles(ParticleTypes.LARGE_SMOKE,
                    victim.getX(), victim.getY() + 1.0, victim.getZ(),
                    12, // 粒子数量
                    0.4, 0.6, 0.4, // 扩散范围
                    0.03 // 初始速度
            );

            // 紫色魔法粒子表示诅咒效果
            serverWorld.spawnParticles(ParticleTypes.WITCH,
                    victim.getX(), victim.getY() + 0.5, victim.getZ(),
                    8, // 粒子数量
                    0.3, 0.4, 0.3, // 扩散范围
                    0.08 // 初始速度
            );

            // 在攻击者武器位置生成一些诅咒粒子表示触发
            serverWorld.spawnParticles(ParticleTypes.SMOKE,
                    attacker.getX(), attacker.getY() + 1.2, attacker.getZ(),
                    5, // 粒子数量
                    0.2, 0.3, 0.2, // 扩散范围
                    0.02 // 初始速度
            );
        }
    }

    /**
     * 获取负面状态效果列表（移除挖掘疲劳和浮空）
     */
    private static List<RegistryEntry<StatusEffect>> getNegativeEffects() {
        List<RegistryEntry<StatusEffect>> negativeEffects = new ArrayList<>();

        // 添加各种负面效果（移除了挖掘疲劳和浮空）
        negativeEffects.add(StatusEffects.POISON);         // 中毒
        negativeEffects.add(StatusEffects.WEAKNESS);       // 虚弱
        negativeEffects.add(StatusEffects.SLOWNESS);       // 缓慢
        negativeEffects.add(StatusEffects.NAUSEA);         // 反胃
        negativeEffects.add(StatusEffects.BLINDNESS);      // 失明
        negativeEffects.add(StatusEffects.HUNGER);         // 饥饿
        negativeEffects.add(StatusEffects.WITHER);         // 凋零
        negativeEffects.add(StatusEffects.UNLUCK);         // 霉运
        negativeEffects.add(StatusEffects.DARKNESS);       // 黑暗

        // 过滤掉null值和过于危险的效果
        negativeEffects.removeIf(effect -> effect == null ||
                effect == StatusEffects.INSTANT_DAMAGE ||
                effect == StatusEffects.BAD_OMEN);

        return negativeEffects;
    }

    /**
     * 获取指定装备槽位的GloomCurse附魔等级
     */
    private static int getGloomCurseLevel(LivingEntity entity, EquipmentSlot slot) {
        ItemStack stack = entity.getEquippedStack(slot);
        if (stack.isEmpty()) {
            return 0;
        }

        var enchantments = EnchantmentHelper.getEnchantments(stack);
        return enchantments.getEnchantments().stream()
                .filter(entry -> {
                    if (entry.getKey().isPresent()) {
                        return entry.getKey().get().getValue().toString().equals("lucifer_treasure:gloom_curse");
                    }
                    return false;
                })
                .mapToInt(entry -> enchantments.getLevel(entry))
                .max()
                .orElse(0);
    }

    @Override
    public void apply(ServerWorld world, int level, EnchantmentEffectContext context, Entity target, Vec3d pos) {
        // 主要逻辑在事件监听器中处理
        // 这里可以添加持续的诅咒效果
        if (target instanceof LivingEntity living) {
            // 添加微妙的诅咒粒子效果表示附魔存在
            world.spawnParticles(ParticleTypes.SMOKE,
                    target.getX(), target.getY() + 0.1, target.getZ(),
                    1, 0.1, 0.1, 0.1, 0.01);
        }
    }

    @Override
    public MapCodec<? extends EnchantmentEntityEffect> getCodec() {
        return CODEC;
    }
} 